package com.whmall.service.crm.module.supplierreview.impl;

import com.whmall.service.crm.module.supplierreview.SupplierReviewTagManager;
import com.whmall.service.crm.module.supplierreview.entity.SupplierReviewTagVO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 基于Redis的供应商评论标签管理器
 *
 * @author alex
 * @since 2021/1/18
 */
@Component
@RequiredArgsConstructor
public class RedisSupplierReviewTagManager implements SupplierReviewTagManager {
    private final static String REDIS_KEY = "$supplier_review_tag";
    private final static String REDIS_KEY2 = "$dict$supplier_user_review_tag";
    private final RedisTemplate<String, SupplierReviewTagVO> redisTemplate;

    @Override
    public SupplierReviewTagVO findById(Integer tagId) {
        SupplierReviewTagVO category = hashOperators().get(tagId);
        if (null == category) {
            category = hashOperators2().get(tagId);
            if (null == category) {
                return null;
            }
        }

        category.setId(tagId);
        return category;
    }

    @Override
    public List<SupplierReviewTagVO> findByIds(List<Integer> tagIds) {
        if (null == tagIds || tagIds.isEmpty()) {
            return Collections.emptyList();
        }

        Map<Integer, SupplierReviewTagVO> entries = hashOperators().entries();
        entries.putAll(hashOperators2().entries());
        return entries.entrySet().stream()
                .map(e -> {
                    e.getValue().setId(e.getKey());
                    return e.getValue();
                })
                .filter(e -> tagIds.contains(e.getId()))
                .sorted(Comparator.comparing(e -> tagIds.indexOf(e.getId())))
                .collect(Collectors.toList());
    }

    @Override
    public List<SupplierReviewTagVO> findAll() {
        Map<Integer, SupplierReviewTagVO> entries = hashOperators().entries();
        entries.putAll(hashOperators2().entries());
        if (null == entries) {
            return Collections.emptyList();
        }
        entries.forEach((k, v) -> v.setId(k));
        return new ArrayList<>(entries.values());
    }

    private BoundHashOperations<String, Integer, SupplierReviewTagVO> hashOperators() {
        BoundHashOperations<String, Integer, SupplierReviewTagVO> boundHashOperations = redisTemplate.boundHashOps(REDIS_KEY);
        return boundHashOperations;
    }

    private BoundHashOperations<String, Integer, SupplierReviewTagVO> hashOperators2() {
        BoundHashOperations<String, Integer, SupplierReviewTagVO> boundHashOperations = redisTemplate.boundHashOps(REDIS_KEY2);
        return boundHashOperations;
    }
}
